package org.jsola.hr.web;

import lombok.extern.slf4j.Slf4j;
import org.jsola.hr.common.wechat.*;
import org.jsola.hr.constant.HrConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author JanusMix
 */
@Slf4j
@Controller("hrWeChatOfficialAccountZhiXinRenController")
@RequestMapping(HrConstants.API_PATH + "/v1/weChatOfficialAccountZhiXinRen")
public class WeChatOfficialAccountZhiXinRenController implements WeChatOfficialAccountControllerAPI {


    @Autowired
    private MessageHandlerUtil messageHandlerUtil;

    @Autowired
    private WeChatEventZhiXinRen weChatEventZhiXinRen;

    @Override
    @GetMapping(value = "/weChatHandle")
    public void weChatGet(
            String signature,
            String timestamp,
            String nonce,
            String echostr,
            HttpServletRequest request,
            HttpServletResponse response) {
        PrintWriter out = null;
        try {
            request.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.write(echostr);
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            log.info("weChatHandle参数：{}，{}，{}",signature, timestamp, nonce);
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                log.info("连接微信公众号平台测试成功！");
            }
        } catch (Exception e) {
            log.error("连接微信公众号平台测试失败！", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    @Override
    @PostMapping(value = "/weChatHandle")
    public void weChatPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接受微信推送事件的一个接口
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String result = "";

        PrintWriter out = null;
        try {
            Map<String, String> map = MessageHandlerUtil.parseXml(request);
            // 租户id
            String tenantId = request.getParameter("tenantId");
            // 公众号名称
            String account = request.getParameter("account");
            // 公众号类型（admin是管理端）
            String type = request.getParameter("type");
            log.info("微信回调, map:{},type:{}, 租户id: {},公众号名称: {}", map, type, tenantId, account);
            switch (map.get("MsgType")) {
                //根据时间类型不同，进行相应的回复
                case "event":
                    result = weChatEventZhiXinRen.choose(map, tenantId, account, type);
                    request.setCharacterEncoding("UTF-8");
                    out = response.getWriter();
                    out.write(result);
                    return;
                case "text":

                    return;
                case "image":

                    break;
                case "voice":

                    break;
                case "video":

                    break;
                case "shortvideo":

                    break;
                case "location":

                    break;
                case "link":

                    break;
                default:
                    break;
            }

            String content = ("谢谢您关注" + account);
            result = BuildWXMessage.buildTextMessage(map, content);

            log.info(result);
            if ("".equals(result)) {
                result = "未正确响应";
            }
        } catch (Exception e) {
            log.error("发生异常：", e);
        }


        try {
            request.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.write(result);
        } catch (Exception e) {
            log.error("连接微信公众号平台测试失败！", e);
        } finally {
            out.close();
        }
    }

    /**
     * 创建自定义菜单:
     */
    @RequestMapping("/createWeChatMenu")
    @ResponseBody
    public String createWeChatMenu() {
        String appId = "wx96ec12f2148c28f5";
        String appSecret = "c65581791a9d6a800fe04ce587468f52";
        String accessToken = MessageHandlerUtil.getAccessToken(appId, appSecret).getAccessToken();
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        log.info("发送的url" + tokenUrl);
        /**
         * 复制方便
         * {
         *     "button": [
         *         {
         *             "type": "view",
         *             "name": "快速了解",
         *             "url": "https://zhixinren.work/"
         *         },
         *         {
         *             "name": "快捷入口",
         *             "sub_button": [
         *                 {
         *                     "type": "miniprogram",
         *                     "name": "员工端",
         *                     "url": "https://zhixinren.work/",
         *                     "appid": "wxc3bf1c647f052f0e",
         *                     "pagepath": "pages/index/index"
         *                 },
         *                 {
         *                     "type": "miniprogram",
         *                     "name": "管理端",
         *                     "url": "https://zhixinren.work/",
         *                     "appid": "wx76d5e5e57c7e17f8",
         *                     "pagepath": "pages/home/index"
         *                 },
         *                 {
         *                     "type": "miniprogram",
         *                     "name": "极聘",
         *                     "url": "https://zhixinren.work/",
         *                     "appid": "wxd36bce495288ae2b",
         *                     "pagepath": "pages/home/index"
         *                 }
         *             ]
         *         },
         *         {
         *             "name": "申请试用",
         *             "sub_button": [
         *                 {
         *                     "type": "view",
         *                     "name": "立即申请",
         *                     "url": "https://zhixinren.work/contactUs.html"
         *                 },
         *                 {
         *                     "type": "click",
         *                     "name": "专属客服",
         *                     "key": "dedicatedCustomer"
         *                 }
         *             ]
         *         }
         *     ]
         * }
         */
        String menu = "{\n" +
                "    \"button\": [\n" +
                "        {\n" +
                "            \"type\": \"view\",\n" +
                "            \"name\": \"快速了解\",\n" +
                "            \"url\": \"https://zhixinren.work/\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"快捷入口\",\n" +
                "            \"sub_button\": [\n" +
                "                {\n" +
                "                    \"type\": \"miniprogram\",\n" +
                "                    \"name\": \"员工端\",\n" +
                "                    \"url\": \"https://zhixinren.work/\",\n" +
                "                    \"appid\": \"wxc3bf1c647f052f0e\",\n" +
                "                    \"pagepath\": \"pages/index/index\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"miniprogram\",\n" +
                "                    \"name\": \"管理端\",\n" +
                "                    \"url\": \"https://zhixinren.work/\",\n" +
                "                    \"appid\": \"wx76d5e5e57c7e17f8\",\n" +
                "                    \"pagepath\": \"pages/home/index\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"miniprogram\",\n" +
                "                    \"name\": \"极聘\",\n" +
                "                    \"url\": \"https://zhixinren.work/\",\n" +
                "                    \"appid\": \"wxd36bce495288ae2b\",\n" +
                "                    \"pagepath\": \"pages/home/index\"\n" +
                "                }\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"申请试用\",\n" +
                "            \"sub_button\": [\n" +
                "                {\n" +
                "                    \"type\": \"view\",\n" +
                "                    \"name\": \"立即申请\",\n" +
                "                    \"url\": \"https://zhixinren.work/contactUs.html\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"type\": \"click\",\n" +
                "                    \"name\": \"专属客服\",\n" +
                "                    \"key\": \"dedicatedCustomer\"\n" +
                "                }\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            URL url = new URL(tokenUrl);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");

            http.connect();
            OutputStream os = http.getOutputStream();
            //传入参数
            os.write(menu.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, StandardCharsets.UTF_8);
            return "返回信息" + message;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "createMenu 失败";
    }

    /**
     * 删除自定义菜单:
     */
    @RequestMapping("/deleteWeChatMenu")
    @ResponseBody
    public String deleteWeChatMenu() {
        // TODO 写入appid,秘钥
        String appId = "";
        String appSecret = "";
        String accessToken = MessageHandlerUtil.getAccessToken(appId, appSecret).getAccessToken();
        String action = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken;
        try {
            URL url = new URL(action);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

            http.connect();
            OutputStream os = http.getOutputStream();
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            return "deleteMenu返回信息:" + message;
        } catch (Exception e) {
           log.error("deleteWeChatMenu异常：", e);
        }
        return "deleteMenu 失败";
    }
}
